import base64
import os
import random
import re
import string
import subprocess
import time

from flask_restful import Resource, reqparse
from flask import make_response, jsonify

# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('markdown', type=str, required=True, help='markdown is required.')

# 读取doc格式的文件
class markdown_word(Resource):
    def post(self):
        args = parser.parse_args()
        markdown_text: str = args.get('markdown')

        # 获取当前文件的绝对路径
        current_file_path = os.path.abspath(__file__)

        # 获取当前文件的父级目录
        parent_directory = os.path.dirname(current_file_path)

        # 获取父级目录的父级目录
        grandparent_directory = os.path.dirname(parent_directory)

        # 获取父级目录的父级目录的绝对路径
        absolute_grandparent_directory = os.path.abspath(os.path.dirname(grandparent_directory))

        # 生成一个包含指定长度随机字符的字符串
        random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) + str(
            int(time.time()))


        pattern = r"```mermaid\s+(.*?)```"
        # pattern = r"```.*?([graph|pie|sequenceDiagram|gantt|classDiagram|stateDiagram|journey].*?)```"
        # print(markdown_text, type(markdown_text))
        matches = re.findall(pattern, markdown_text.replace(r'\n', os.linesep), re.DOTALL)
        # print(matches)
        if len(matches) != 0:
            # 循环遍历流程图
            for matche in matches:
                mermaid_code = matche.replace(r'\n', os.linesep)

                # 创建临时文件保存Mermaid代码
                temp_file_path = f'{str(time.time()) + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(10))}.mmd'
                with open(temp_file_path, 'w') as temp_file:
                    temp_file.write(mermaid_code)

                # 调用mmdc命令生成图片
                output_file = f"{absolute_grandparent_directory}/static/{random_string}.png"

                try:
                    # 将Mermaid代码通过stdin传递给mmdc命令
                    result = subprocess.run(['mmdc', '-i', temp_file_path, '-o', output_file, '-w', '7200', '-H', '7200'])
                    if result.returncode == 0:
                        with open(output_file, "rb") as image_file:
                            image_data = image_file.read()
                            base64_data = base64.b64encode(image_data)

                        markdown_text = re.sub(pattern, os.linesep + f"![]({'data:image/png;base64,' + base64_data.decode('utf-8')})" + os.linesep, markdown_text.replace(r'\n', os.linesep), count=1, flags=re.DOTALL)
                    else:
                        # 删除临时文件
                        # os.remove(temp_file_path)
                        raise Exception("执行命令出错")
                except Exception as e:
                    pass

                # 删除临时文件
                os.remove(temp_file_path)


        # 将Markdown转换为Word
        output = subprocess.check_output(['pandoc', '-f', 'markdown', '-t', 'docx'], input=markdown_text.encode())
        # print(f"{absolute_grandparent_directory}/static/{random_string}.docx")


        with open(f"{absolute_grandparent_directory}/static/{random_string}.docx", 'wb') as f:
            f.write(output)

        # 创建响应
        # response = make_response(output)
        # response.headers['Content-Disposition'] = 'attachment; filename=converted.docx'
        # response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        return {
            "url": f"http://8.219.60.106:10002/static/{random_string}.docx"
        }
